package com.xbongbong.pro.dataset.node;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.xbongbong.paas.enums.bi.DataSetNodeTypeEnum;
import com.xbongbong.pro.bi.commons.helper.StringHelper;
import com.xbongbong.pro.bi.commons.sql.SqlBuilderHandler;
import com.xbongbong.pro.dataset.pojo.GroupNode;
import com.xbongbong.pro.statistic.pojo.dto.SqlParseDTO;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author gzt
 * @version 1.0
 * @Description -
 * @datetime - 2022/5/23-11:13
 * @since v1.0
 */
@Component
public class GroupNodeStrategy implements NodeStrategy {
    @Override
    public void parseNodeToSql(SqlParseDTO sqlParseDTO) {
        String nodeId = sqlParseDTO.getNodeId();
        JSONObject jsonObject = sqlParseDTO.getJsonObject();
        GroupNode groupNode = jsonObject.toJavaObject(new TypeReference<GroupNode>() {});
        List<String> inputList = groupNode.getInput();
        int size = inputList.size();
        if (size != 1){return;}
        String node = inputList.get(0);
        Map<String, String> sqlNodes = SQL_NODES_THREAD_LOCAL.get();
        String node1Sql = sqlNodes.get(node);
        SqlBuilderHandler sqlBuilder = SqlBuilderHandler.start();
        List<HashMap<String,Object>> listFields = groupNode.getGroup();
        String groupAttrs = listFields.stream().map(field -> {
            String originalAttr = StringHelper.getString(field,"originalAttr");
            return originalAttr;
        }).collect(Collectors.joining(","));

        List<HashMap<String,Object>> sumFields = groupNode.getSum();
        String attrs = sumFields.stream().map(field -> {
            String aggType = StringHelper.getString(field,"aggType");
            String attr = StringHelper.getString(field,"attr");
            String appendAttr = aggType+"("+attr+")";
            return appendAttr;
        }).collect(Collectors.joining(","));

        String sql = sqlBuilder.select(attrs)
                .from(node1Sql)
                .groupBy(groupAttrs).end().getSql();
        sqlNodes.putIfAbsent(nodeId,sql);

    }

    @Override
    public String getNodeType() {
        return DataSetNodeTypeEnum.GROUP.getAlias();
    }

    @Override
    public String getParseSql(String nodeId) {
        return null;
    }
}
